package com.onlineshop.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class FileUploadUtil {
    // 文件上传路径（相对于Web应用程序根目录）
    private static final String UPLOAD_DIRECTORY = "uploads";
    // 最大文件大小（10MB）
    private static final int MAX_FILE_SIZE = 10 * 1024 * 1024;
    // 最大请求大小（20MB）
    private static final int MAX_REQUEST_SIZE = 20 * 1024 * 1024;

    public static Map<String, String> parseRequest(HttpServletRequest request) {
        Map<String, String> formFields = new HashMap<>();

        // 检查请求是否为multipart
        if (!ServletFileUpload.isMultipartContent(request)) {
            return formFields;
        }

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MAX_FILE_SIZE);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);
        // 设置最大请求值
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 构造上传路径（相对于Web应用程序根目录）
        String uploadPath = request.getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            // 解析请求
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // 普通表单字段
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString("UTF-8");
                    formFields.put(fieldName, fieldValue);
                } else {
                    // 文件字段
                    String fileName = item.getName();
                    if (fileName != null && !fileName.isEmpty()) {
                        // 生成唯一文件名
                        String uniqueFileName = UUID.randomUUID().toString() + "_" + fileName;
                        String filePath = uploadPath + File.separator + uniqueFileName;
                        File storeFile = new File(filePath);

                        // 保存文件
                        item.write(storeFile);

                        // 将文件名保存到表单字段中
                        formFields.put("image", uniqueFileName);
                    }
                }
            }
        } catch (FileUploadException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return formFields;
    }
}